function _gel(obj,id){return obj.getElementById(id);}

function onKU(e){if(e.keyCode==13){Search(); addEntry()}}

function addEntry(){
  var fhService = Components.classes["@mozilla.org/satchel/form-history;1"].
                     getService(Components.interfaces.nsIFormHistory2);
  fhService.addEntry("myAutocomplete", _gel(document,'query').value);
}

function onLC(e){
  // Only links that would open inside the sidebar cause the 
  // sidebar browser to hide itself (to avoid seeing the
  // style changes) all others leave the browser alone
  if(e.target.target!='_blank') {
    _gel(document,'tbrowser').style.display='none';
    _gel(document,'progbar').style.display='';}    
}

function onSBDCL(e){var g=_gel(e.target,'query');  if(g) g.focus();}

function onDCL(e){
  // Handle OnDOMContentLoaded
  var b=_gel(document,'tbrowser'); // Get the browser window
  // Proceed if we have a document
  if(b.currentURI.path=='blank') return;
  
  // Get the loaded document
  var d=b.contentDocument;

  // Add a listener to all links so to hide the browser window while loading the 
  // document to avoid seeing the style changes being applied
  var links=d.links;
  for(i=0;i<links.length;i++){links[i].addEventListener('click',onLC,false);}

  // Customize some styles--for better display
  var style=d.createElement('style');
  style.type = 'text/css';
  style.innerHTML = 'body{background-color:#FFFFE1; margin:2px;}';
  style.innerHTML += '* {font-size: 11px !important;} ul{padding-left:0px;list-style-position: inside;}';
  style.innerHTML+= '.title-td{white-space:normal} td{white-space:normal}';
  style.innerHTML+= '.top-border{font-size:1px !important;} ';
  
  // DRAE-only and WR-only style change
  if(d.body.innerHTML.match('Aviso') && b.currentURI.host.match('rae.es') ) 
    style.innerHTML+= 'P{margin-left:0px !important;}';
  if(b.currentURI.host.match('wordreference.com')){
    style.innerHTML+='h2{font-size:14px;color:#000} a > .namecell{font-size:inherit; color:inherit} td.content{width:90%}';
    style.innerHTML+='.namecell{display:none !important} .searchbox{display:none !important}';
    style.innerHTML+='#Otbl{width:100% !important;} .layout{background:transparent!important} tr.even{background:#FFFEF2 !important';
  }
  // Append the custom style into the document head
  d.getElementsByTagName('head')[0].appendChild(style);
  
  // Even with the above styles we don't get everything. Luckyly for both  
  //  cases it's the TD elements we need to look at
  var tds=d.getElementsByTagName('TD');
  for(var i=0;i<tds.length;i++){
    if(tds[i].id=='BABID_CPTitle'){
      //// BABYLON RESULTS ////
      // Adjust the result "title" to allow it to fit in the sidebar
      var bt=tds[i];
      bt.noWrap=false;
      bt.style.whiteSpace='normal';
      bt.previousSibling.style.width='1%';
      bt.nextSibling.style.width='1%';
    } else if(tds[i].className=='barra'){
      //// DRAE RESULTS ////
      // Hide the header 
      tds[i].parentNode.parentNode.parentNode.style.display='none';
    }  
  }
  
  // show the browser again and hide the progess bar
  _gel(document,'progbar').style.display='none';
  b.style.display=''; 
}

function Search(obj){
  // Perform the search
  if(obj==null) obj=document;
  var x=_gel(obj,'choice');
  var b=_gel(obj,'tbrowser');
  var q=_gel(obj,'query');
  if(q.value=="") return; 
  // hide the browser and show the progress bar
  b.style.display='none';
  _gel(obj,'progbar').style.display='';
  
  // choose the right url for search
  var url='http://info.babylon.com/onlinebox.cgi?rt=ol&uil=en&term={SEARCH_TERM}&cid=CD1893&tid=BabylonSearch&tl=es';
  if(x.value=='1') url='http://buscon.rae.es/draeI/SrvltGUIBusUsual?TIPO_BUS=1&LEMA={SEARCH_TERM}';
  if(x.value=='2') url='http://mini.wordreference.com/mini/index.aspx?w={SEARCH_TERM}&dict=enes';
  b.loadURI(url.replace('{SEARCH_TERM}',q.value));
}

function ContextSearch(srchType){
  // search/translate from the context menu
  var term=window.getBrowserSelection(150); // get selected text
  toggleSidebar('viewTransSidebar',true); // show the sidebar
  var d=_gel(document,'sidebar').contentDocument; // get the sidebar document
  // Get the query element in the translation sidebar. If the sidebar is still 
  // loading this will return null, so we just wait for it to become available
  var x=_gel(d,'query');
  if(x){  
    // the sidebar is likely open and the query box is available
    x.value=term;
    _gel(d,'choice').value=(srchType=='B'?'0':(srchType=='W'?'2':'1'))
    Search(d);
    //alert(waitCycles);
  }else{
    // the sidebar is still not available, so check again in 0.5 seconds
    setTimeout("finishSearch('"+term+"','"+srchType+"')",500);
    waitCycles+=1;//increment wait counter
  }
}

function finishSearch(term,srchType){
  // try again to put the selected text in the query box
  var d=_gel(document,'sidebar').contentDocument;
  var x=_gel(d,'query');
  if(x){  
    // the sidebar is likely open and the query box is available
    x.value=term;
    _gel(d,'choice').value=(srchType=='B'?'0':(srchType=='W'?'2':'1'))
    Search(d);
    //alert(waitCycles);
  }else if(waitCycles<=10){
    // the sidebar is still not available
    setTimeout("finishSearch('"+term+"','"+srchType+"')",500);
    waitCycles+=1;//increment wait counter, we'll only wait a total of 10 checks
  }
}


var waitCycles=0;
